package com.tanhua.dubbo.api;


import com.tanhua.model.mongo.ReceiveCall;
import com.tanhua.model.mongo.SendCall;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CallApiImpl implements CallApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveSendCall(SendCall sendCall) {
        mongoTemplate.save(sendCall);
    }

    @Override
    public void saveReceiveCall(ReceiveCall receiveCall) {
        mongoTemplate.save(receiveCall);
    }

    @Override
    public SendCall getIsNotZero(List<Long> friendId) {
        //拿到随机一个值
//        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("isPickUp").is("0")), Aggregation.sample(1));
//        AggregationResults<SendCall> aggregate = mongoTemplate.aggregate(aggregation, SendCall.class, SendCall.class);
//        SendCall uniqueMappedResult = aggregate.getUniqueMappedResult();

        //保证原子性
        Query query = Query.query(Criteria.where("isPickUp").is("0").and("userId").nin(friendId)).with(Sort.by(Sort.Direction.ASC, "createdDate")).limit(1);
        Update update = Update.update("isPickUp","1");
        FindAndModifyOptions options = new FindAndModifyOptions();
        // 返回当前最新值
        options.returnNew(true);

        return  mongoTemplate.findAndModify(query, update, options, SendCall.class);

    }


}
